package com.example.hobbyplanetserve.utils;

import com.example.hobbyplanetserve.entity.MyTUserDetail;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * 获取当前用户的工具类
 */

@Component
public class SecurityUtils {
    /**
     * 获取当前登录的自定义用户信息
     */
    public static MyTUserDetail getCurrentUserDetail() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof MyTUserDetail) {
            return (MyTUserDetail) authentication.getPrincipal();
        }
        return null;
    }

    /**
     * 获取当前登录的用户名
     */
    public static String getCurrentUsername() {
        MyTUserDetail userDetail = getCurrentUserDetail();
        if (userDetail != null) {
            return userDetail.getUsername();
        }
        return null;
    }
}
